package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wanghaotian
 * time:2022/12/12,0012 19:07
 * description:
 */

@Controller
public class UserAuthController {

    @RequestMapping("/doLogin")
    @ResponseBody
    public Result doLogin(String username,String password,boolean rem){
        try {
            Subject subject = SecurityUtils.getSubject();
            password = new Md5Hash(password,username,1024).toString();
            System.out.println("加密后"+password);
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            if(rem){
                token.setRememberMe(true);
            }
            subject.login(token);
        } catch (UnknownAccountException e) {
            return Result.error("用户名不存在");
        } catch (IncorrectCredentialsException e) {
            return Result.error("密码不对");
        } catch (LockedAccountException e) {
            return Result.error("账号被锁定");
        }
        return Result.ok("登录成功");
    }

    @RequestMapping("/doLogin1")
    @ResponseBody
    public String doLogin1(String username,String password,boolean rem){
        Session session = null;
        try {
            Subject subject = SecurityUtils.getSubject();
            session = subject.getSession();
            password = new Md5Hash(password,username,1024).toString();
            System.out.println("加密后"+password);
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            if(rem){
                token.setRememberMe(true);
            }
            subject.login(token);
            session.setAttribute("username", username);
            return "/index.jsp";
        } catch (Exception e) {
            session.setAttribute("error", e.getMessage());
        }
        return "/login.jsp";
    }

    @RequestMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok("退出成功");
    }

}
